var WD_CIG = {dtype:"hot",pageIndex:0,heightOffset:0}

$(function(){
    
    $(".answer-editor").on("keypress",function(e){
        var ev = document.all ? window.event : e;
        if(ev.keyCode==13 && document.queryCommandSupported && document.queryCommandSupported("insertHTML")) {
            document.execCommand("insertHTML", false, "<br><br>");
            return false;
        }
        return true;
    });
    
    //问答详情右上角菜单
    $('.title .titleToggle').on('click',function(e){
        $('.title-toggle').slideToggle();
        $(document).one("click", function(){
            $(".title-toggle").hide();
        });
        e.stopPropagation();
    });
    $.fn.wenda_nav = function(){
        var _self = $(this),_list = $("#content-list"),
            _ul = _self.find("ul"),
            _li = _ul.find("li"),
            load_false = true;
        var S = function(){
            if(!load_false){return;}
            WD_CIG.pageIndex = 0;
            layer.open({type:2});
            doRequest("/ajax/ajax_fetch_wenda_json",{dType:WD_CIG.dtype},true,function(data){
                load_false = true;
                layer.closeAll();
                $(".loading").hide();
                return _list.html(data.htmlData).attr("scrollpagination","enabled");
            },function(data){});
        }
        _li.on("click",function(){
            var _this = $(this);
            WD_CIG.dtype = _this.attr("data-type");
            scrollPagination_obj.contentData.dType = WD_CIG.dtype;
            if(_this.hasClass('active') ){
                return;
            }else{
                _this.addClass('active');
                _this.find('span').stop().animate({height:'45px'},300);
                _this.siblings().removeClass('active');
                _this.siblings().find('span').stop().animate({height:'0px'},300);
            }
            return setTimeout(function(){S();},300);
        });
        
    }
    $(".wenda-nav").wenda_nav();
    //举报相关
    $('._report_btn').on("click",function(e){
        e.stopPropagation();
        $(".title-toggle").hide();
        return $(this).report();
    });
    $('body').delegate("._report","click",function(e){
        e.stopPropagation();
        $(".title-toggle").hide();
        return $(this).report();
    });
    $("body").delegate("._reply","click",function(){
        return reply_comment_fn({answerId:$("#answer-info").attr("data-aid"),replyId:$(this).attr("data-rid"),replyerName:$(this).attr("data-rname")});
    });
    $("body").delegate("#content-list li","click",function(){
        return $(this).find("._reply").click();
    });
    $("body").delegate("#content-list li .name","click",function(e){
        e.stopPropagation();
    });
    //关注操作
    $("._care_btn").on("click",function(){
        if(!_is_login()){return;}
        var _self = $(this),_val = 1 - _self.attr("data-val"),_info=$("#wenda-info");
        if(is_login.uuid == _info.attr("data-uid")){$.mvalidateTip("不能关注自己的问答哦");return;}
        _self.attr("data-val",_val);
        if(_val == 1){
            _self.parent("li").addClass("follow2").find("i").text("已关注");
            $.mvalidateTip("关注成功");
        }else{
            _self.parent("li").removeClass("follow2").find("i").text("关注");
            $.mvalidateTip("已取消关注");
        }
        doRequest("/ajax/ajax_wd_care",{value:_val,wenda_id:_info.attr("data-wid"),uuid:_info.attr("data-uid"),stampTime:Math.random()},true,function(data){
            
        },function(data){$.mvalidateTip(data.errorMsg);});
    });
    //最佳答案操作
    $("body").delegate("._answer","click",function(){
        if(!_is_login()){return;}
        var _self = $(this),_li = _self.parents("li");
        var _wid = $("#wenda-info").attr("data-wid"),_aid = _li.attr("data-aid"),_uid = $("#wenda-info").attr("data-uid");
        layer.open({
            content: '确认选为最佳答案吗',btn: ['确认', '取消'],yes: function(index){
                layer.close(index);
                doRequest("/ajax/ajax_wd_best",{wendaId:_wid,answerId:_aid,uuid:_uid,stampTime:Math.random()},true,function(data){
                    $.mvalidateTip(data.errorMsg);
                    _self.removeClass("_answer").addClass("active").find("i").text("最佳答案");
                    _li.parent("ul").find("._answer").remove();
                },function(data){
                    $.mvalidateTip(data.errorMsg);
                });
            }
        });
    });
    //关注操作
    $(".fct_follow").on("click",function(){
        if(!_is_login()){return;}
        var _self = $(this),_val = 1 - _self.attr("data-val"),_info=$("#answer-info");
        if(is_login.uuid == _info.attr("data-uid")){$.mvalidateTip("不能关注自己哦");return;}
        _self.attr("data-val",_val);
        if(_val == 1){
            _self.addClass("follow2").find("i").text("已关注");
            $.mvalidateTip("关注成功");
        }else{
            _self.removeClass("follow2").find("i").text("关注");
            $.mvalidateTip("已取消关注");
        }
        doRequest("/ajax/cancel_fan_act",{author_id:_info.attr("data-uid"),is_fan:_val},true,function(data){},function(data){$.mvalidateTip(data.errorMsg);});
    });
    //答案详情点赞操作
    $(".fct_like").on("click",function(){
        if(!_is_login()){return;}
        var _self = $(this),_val = 1 - _self.attr("data-val"),_info=$("#answer-info");
        if(_self.attr("data-val") == 1){$.mvalidateTip("已经点赞过该答案了");return;}
        
        doRequest("/ajax/ajax_wd_up",{value:_val,answerId:_info.attr("data-aid"),answerUid:_info.attr("data-uid"),stampTime:Math.random()},true,function(data){
            _self.attr("data-val",_val);
            $.tipsBox({obj:_self,str: "+1",callback: function(){}});
            _self.addClass("icon-praise2");
        },function(data){
            $.mvalidateTip(data.errorMsg);
        });
    });
    //答案列表点赞操作
    $("body").delegate(".fct-list-like","click",function(){
        if(!_is_login()){return;}
        var _self = $(this),_val = 1 - _self.attr("data-val");
        if(_self.attr("data-val") == 1){$.mvalidateTip("已经点赞过该答案了");return;}
        doRequest("/ajax/ajax_wd_up",{value:_val,answerId:_self.attr("data-aid"),answerUid:_self.attr("data-uid"),stampTime:Math.random()},true,function(data){
            _self.attr("data-val",_val);
            $.tipsBox({obj:_self,str: "+1",callback: function(){}});
            _self.removeClass("col-grey999").addClass("col-redf941").find("i").text(data.count);
        },function(data){
            $.mvalidateTip(data.errorMsg);
        });
    });
    /**评论右侧隐藏菜单start*/
    $("body").delegate('.menu-toggle a',"click",function(){
        $(this).parent().fadeOut();
    });
    $('body').delegate(".menuToggle","click",function(e){
        
        var _tog = $(this).parent().children('.menu-toggle');
        $(".menu-toggle").each(function(index,obj){
            $(this)[0] === _tog[0] ? $(this).stop().toggle(100) : $(this).hide();
        });
        $(document).one("click",function(){
            $(".menu-toggle").hide();
        });
        $(".title-toggle").stop().fadeOut();
        e.stopPropagation();
    });
    $('body').delegate(".menu-toggle","click",function(e){
        e.stopPropagation();
    });
    /**评论右侧隐藏菜单end*/
    //展开收起
    $('.answer .hide').click(function(){
        if ($(this).hasClass('show') ){
            $(this).removeClass('show');
            $(this).parent().children('.text-all').animate({height:'0px'},0);
        }else{
            $(this).addClass('show');
            $(this).parent().children('.text-all').animate({height:'100%'},0);
        }
    });
    //获取到留言区的位置
    $('.bottom .bottom-article-details a.icon-comments').click(function(){
        mtop = $('.sliding-jq').offset().top;
        $('html,body').stop().animate({scrollTop: mtop - '50' + 'px'},800);
    });
    
    $(".reply-content-a").on("click",function(){
        return reply_comment_fn({answerId:$("#answer-info").attr("data-aid"),replyId:"",replyerName:""});
    });
    
    //分享问答窗口
    $.fn.share_wenda = function(flag){
        var _share_box = $(".share-wenda-box"),_ainfo = $("#wenda-info"),
            _content_box = _share_box.find(".share-content-box"),
            _lis = _share_box.find("li"),
            _close = _share_box.find("._close");
        var S = function(){
            _share_box.stop().fadeIn();
            _content_box.animate({'bottom':'0px'},500);
        }
        var F = function(){//移除分享框
            _share_box.stop().fadeOut();
            _content_box.stop().animate({'bottom':'-200px'},500);
        }
        _share_box.one("click",function(){
            return F();//阴影处移除
        });
        _close.on("click",function(){
            return F();
        });
        _content_box.on("click",function(e){
            e.stopPropagation();
        });
        _lis.css("width","50%");
        if(flag){
            _lis.unbind("click").on("click",function(){
                var _li = $(this),_type = _li.attr("data-type");
                var _title = _ainfo.attr("data-title"),_desc = _ainfo.attr("data-desc"),_link = _ainfo.attr("data-link"),_thumb = _ainfo.attr("data-thumb");
                var from = "（分享自@弹溜溜-杭州乌云网络）";
                var z = encodeURIComponent(_title),s = "",u = encodeURIComponent(_link),img = _thumb;
                r = encodeURIComponent("--弹溜溜，儿时快乐的指尖回忆。在这里发现更多志趣相投的伙伴；参与最前沿的互联网金融体验；探索最酷最好玩的生活..." + (_type == "sina" ? from : "")) ;
                switch(_type){
                    case "sina"://微博
                        t = "弹溜溜社区-新浪",e = "http://service.weibo.com/share/share.php?url={0}&title="+ z + s + r +"&pic={1}", n = String.Format(e, u ,img);
                    break;
                    case "qq-space"://qq空间
                        t = "弹溜溜社区-QQ空间", e = "http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url={0}&title=" + z + "&desc={1}&summary={1}", n = String.Format(e, u, (z + r));
                    break;
                }
                
                try {
                    window.open(n);
                } catch (u) {
                    window.open(n, t);
                }
                return;
            });
        }
        return S();
    }
    //分享答案窗口
    $.fn.share_answer = function(flag){
        var _share_box = $(".share-answer-box"),_ainfo = $("#art-info"),
            _content_box = _share_box.find(".share-content-box"),
            _lis = _share_box.find("li"),
            _close = _share_box.find("._close");
        var S = function(){
            _share_box.stop().fadeIn();
            _content_box.animate({'bottom':'0px'},500);
        }
        var F = function(){//移除分享框
            _share_box.stop().fadeOut();
            _content_box.stop().animate({'bottom':'-200px'},500);
        }
        _share_box.one("click",function(){
            return F();//阴影处移除
        });
        _close.on("click",function(){
            return F();
        });
        _content_box.on("click",function(e){
            e.stopPropagation();
        });
        _lis.css("width","50%");
        if(flag){
            _lis.unbind("click").on("click",function(){
                var _li = $(this),_type = _li.attr("data-type");
                var _title = _ainfo.attr("data-title"),_desc = _ainfo.attr("data-desc"),_link = _ainfo.attr("data-link"),_thumb = _ainfo.attr("data-thumb");
                var from = "（分享自@弹溜溜-杭州乌云网络）";
                var z = encodeURIComponent(_title),s = "",u = encodeURIComponent(_link),img = _thumb;
                r = encodeURIComponent("--弹溜溜，儿时快乐的指尖回忆。在这里发现更多志趣相投的伙伴；参与最前沿的互联网金融体验；探索最酷最好玩的生活..." + (_type == "sina" ? from : "")) ;
                switch(_type){
                    case "sina"://微博
                        t = "弹溜溜社区-新浪",e = "http://service.weibo.com/share/share.php?url={0}&title="+ z + s + r +"&pic={1}", n = String.Format(e, u ,img);
                    break;
                    case "qq-space"://qq空间
                        t = "弹溜溜社区-QQ空间", e = "http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url={0}&title=" + z + "&desc={1}&summary={1}", n = String.Format(e, u, (z + r));
                    break;
                }
                
                try {
                    window.open(n);
                } catch (u) {
                    window.open(n, t);
                }
                return;
            });
        }
        return S();
    }
    //分享相关
    $("._share_wenda").on("click",function(){
        var brower = brower_info(),_sinfo = $("#wenda-info");
        var _link = _sinfo.attr("data-link"),_title = _sinfo.attr("data-title"),_desc = _sinfo.attr("data-desc"),_thumb = _sinfo.attr("data-thumb");
        if(brower.is_weixin()){
            return $("#wx-share").share_msg();
        }else if(brower.is_ucBrower() || brower.is_qqBrower()){
            return $(this).share_wenda(),new native_share("share-box",{url:_link,title:_title,desc:_desc,img:_thumb,img_title:_title,from:"弹溜溜"});
        }else{
            return $(this).share_wenda(true); 
        }
    });
    //分享相关
    $("._share_answer").on("click",function(){
        var brower = brower_info(),_sinfo = $("#answer-info");
        var _link = _sinfo.attr("data-link"),_title = _sinfo.attr("data-title"),_desc = _sinfo.attr("data-desc"),_thumb = _sinfo.attr("data-thumb");
        if(brower.is_weixin()){
            return $("#wx-share").share_msg();
        }else if(brower.is_ucBrower() || brower.is_qqBrower()){
            return $(this).share_answer(),new native_share("share-box",{url:_link,title:_title,desc:_desc,img:_thumb,img_title:_title,from:"弹溜溜"});
        }else{
            return $(this).share_answer(true); 
        }
    });
    //分享提示
    $.fn.share_msg = function(){
        var _self = $(this);
        _self.on("click",function(){
            return _self.hide();
        });
        return _self.show();
    }
    
    //提问-第一步
    $.fn.asking_one = function(){
        
        var _self = $(this),_title = _self.find("#title"),
            _content = _self.find("#content"),
            _next_btn = $("#asking-next-btn"),
            _back = $("#wenda-back");
        _back.on("click",function(){
            if(_title.val() != ""){
                layer.open({
                    content: '确定要放弃提问吗',btn: ['狠心放弃', '取消'],yes: function(index){
                        layer.close(index);
                        doRequest("/wenda/asking_cancel",{timestamp:Math.random()},true,function(data){
                            window.location.href = "/wenda.html";
                        },function(data){});
                    }
                });
                return;
            }else{
                window.location.href = "/wenda.html";
            }
        });
        _next_btn.on("click",function(){
            if(!_is_login()){return;}
            
            if(is_mobile != 1){
                layer.open({
                    content: '检测您还未绑定手机哦',btn: ['马上绑定', '取消'],yes: function(index){
                        layer.close(index);
                        window.location.href="/account/bindmobile.html?redirectUrl="+encodeURIComponent(window.location.href);
                    }
                });
                return;
            }
            if(check_str_len(_title.val()) < 5){$.mvalidateTip("标题至少5个字哦");return;}
            layer.open({type:2});
            //请详细描述您的内容~
            var _cont = _content.html() == "请详细描述您的内容~" ? "" : _content.html();
            setTimeout(function(){
                doRequest("/wenda/asking_next",{title:_title.val(),content:_cont},true,function(data){
                    layer.closeAll();
                    window.location.href = data.url;
                },function(data){
                    $.mvalidateTip(data.errorMsg);
                    layer.closeAll();
                });
            },1000);
        });        
    }
    
    //提问-完成
    $.fn.asking_complete = function(){
        var _self = $(this),
            _tags = $("#wenda-tags"),
            _add_tags = $("#add-tags-btn"),
            _ok = $("#btn-complete");
        _add_tags.on("click",function(){
            return tags_show_box();
        });
        //选择标签
        $("body").delegate("#wenda-tags li","click",function(){
            var _s = $(this);
            $(this).hasClass('active') ? $(this).removeClass('active') : $(this).addClass('active');
            if(!check_wenda_tags(_tags)){return;}
        });
        //完成提问
        var flag = true;
        _self.on("click",function(){
            if(!_is_login()){return;}
            if(!flag){$.mvalidateTip("正在处理中");return;}
            var tags = check_tags(_tags);
            if(tags == ""){
                $.mvalidateTip("至少选择一个标签哦");return;
            }
            
            flag = false;
            _self.text("处理中");
            doRequest("/wenda/asking_complete",{tags:tags},true,function(data){
                _self.text("完成");
                window.location.href = data.url;
            },function(data){
                _self.text("完成");
                $.mvalidateTip(data.errorMsg);
            });
        });
    }
    
});
function check_tags(obj){
    var str="",obj = obj.find("li[class='active']");
    if(typeof(obj[0]) && obj.length > 0){
       obj.each(function(index,data){
           if((index+1) < 6){
               str += $(this).attr("data-name")+"_"+$(this).attr("data-tid")+",";
           }
       });
       return str.substring(0,str.length-1);
    }else{
        return "";
    }
}
function check_wenda_tags(obj){
    if((obj.find("li[class='active']")).length == 5){
        $.mvalidateTip("最多只能添加5个标签哦");
        return false;
    }
    return true;
}
//新手标签输入框
function tags_show_box(){
    var _box = $(".tag-content-box"),
        _close = _box.find("._close"),
        _input = _box.find("#tag-content"),
        _wrapper = _box.find("#wrapper-label"),
        _tags = $("#wenda-tags"),
        _add_btn = $("#add-tags-btn"),
        _ul = _wrapper.find("ul");
    var S = function(){
        _add_btn.hide();
        _input.val("");
        _wrapper.hide().find("ul li").remove();
        return _box.stop().fadeIn(),_input.focus();
    }
    var C = function(){
        _add_btn.show();
        _wrapper.hide().find("ul li").remove();
        return _box.stop().fadeOut();
    }
    
    _close.on("click",function(){
        return C();
    });
    
    $("body").delegate("#wrapper-label ul li","click",function(){
        return selected_tag($(this));
    });
    
    _input.on("keyup",function(){
        var _key_tag = $(this).val();
        if(_key_tag == "") {_wrapper.hide();return;}//隐藏搜索框
        _ul.html("");
        _wrapper.show().find("span").text("搜索中...").show();
        doGetRequest("/ajax/seach_wenda_tag",{tag_key:_key_tag},true,function(res){
            var html = res.seachRes;
            if(html == ""){
                _ul.html("");
                _wrapper.find("span").text("匹配为空").show();
            }else{
                setTimeout(function(){
                    _wrapper.find("span").hide();
                    _ul.html("").html(html);
                },500);
            }
        },function(res){});
    });
    
    return S();
}
function selected_tag(obj){
    var _self=obj,_flag=$("#wenda-tags").find("li[data-tid="+_self.attr("seach-tid")+"]");
    if(typeof(_flag[0]) != "undefined"){
        if(_flag.hasClass("active")){
            check_wenda_is_on(_flag);
        }else{
            _flag.addClass("active");
        }
    }else{
        $("#wenda-tags").append("<li data-name='"+_self.attr("seach-name")+"' data-tid='"+_self.attr("seach-tid")+"' class='active'>"+_self.attr("seach-name")+"</li>");
    }
    check_wenda_tags($("#wenda-tags"));
}
function check_wenda_is_on(obj){
    var t=0;
    var tt=setInterval(function(){
        t++;
        $(obj).hasClass('active') ? $(obj).removeClass('active') : $(obj).addClass('active');
        if(t == 4) {clearInterval(tt);}
    },300);
    return;
}

function showWdRead(){
    var _wid=$("#wenda-info").attr("data-wid");
    if(typeof(is_login.uuid) != "" && is_login.uuid == $("#wenda-info").attr("data-uid")){return;}
    doGetRequest("/ajax/ajax_wd_read_up",{wenda_id:_wid,uuid:$("#wenda-info").attr("data-uid"),stamptime:Math.random()},false,function(data){},function(data){});
}
function reply_comment_fn(opt){
    return comment_box_show(opt);
}
function comment_box_show(opt){
    var _content_box = $('.reply-content-box'),
        _bottom_box = $("#bottom-content-box"),
        _text_box = _content_box.find(".reply-text-box"),
        _sbtn = _content_box.find("._send"),
        _cbtn = _content_box.find("._cancel"),
        _content = _content_box.find("#reply-content");
    _sbtn.attr("data-reply-id",opt.replyId);
    
    var S = function(){
        if(opt.replyId != ""){
            _content.val("").attr("placeholder","@"+opt.replyerName+":");
        }else{
            _content.val("").attr("placeholder","做个有观点的人");
        }
        _content_box.stop().fadeIn(100);
        _text_box.stop().fadeIn(100);
        _content.focus(); //明显buga
        _bottom_box.hide();
    }
    var C = function(){
        _content_box.stop().fadeOut();
        _text_box.stop().fadeOut();
        _content.val("");
        _sbtn.attr("data-reply-id","");
        return setTimeout(function(){_bottom_box.show();},800);
    }
    _cbtn.on("click",function(){
        return C();
    });
    var sendFlag = true;
    _sbtn.unbind("click").on("click",function(){
        if(!_is_login()){return false;}
        if(!sendFlag){$.mvalidateTip("请不要频繁操作");return;}
        var _self=$(this),_answer_id=opt.answerId,_ctent=_content.val(),
        _novilad=_self.attr("data-disable-val"),_reply_id=_self.attr("data-reply-id");
        if($.trim(_ctent) == ""){$.mvalidateTip("评论内容不能为空哦！");return;}
        sendFlag = false;_self.addClass("send-load");
        setTimeout(function(){
            doRequest("/ajax/ajax_add_reply",{answerId:_answer_id,replyTxt:_ctent,replyId:_reply_id},true,function(data){
                sendFlag = true;
                _self.removeClass("send-load");
                $.mvalidateTip("评论成功");
                $("#content-list").prepend(data.htmlData);
                $(".icon-comments b").text(data.replyNum);
                return C(),rcomment();
            },function(data){
                sendFlag = true;
                _self.removeClass("send-load");
                $.mvalidateTip(data.errorMsg);
            });
        },1000);
    });
    return S();
}
function rcomment(){
    $li = $("#content-list li");
    if($li.length > 0){
        $("#noresults").hide();
    }else{
        $("#noresults").show();
        $("#nomoreresults").hide();
    }
}